package thread;

import java.lang.management.ManagementFactory;

/**
 * 参考博客：https://blog.csdn.net/xionghan01/article/details/52840358
 * 测试步骤：
 * 1. 每次只在主函数中测试一个always方法，其他的注释掉；
 * 2. 根据打印的pid，使用jstack -l pid 去查看main线程的状态；
 * 3. 还可以使用 jstack pid > /path/to/thread.dump 输出到临时文件中查看。
 */
public class AlwaysAtOneState {

    public static void main(String[] args) {
        System.out.println(pid());
//        runnable();
//        alwaysBlocked();
//        alwaysTimedWaiting();
        alwaysWaiting();
    }

    private static String pid() {
        return ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
    }

    private static void alwaysRunnable() {
        long i = 0;
        while (true) {
            i++;
        }
    }

    public static void alwaysBlocked() {
        final Object lock = new Object();
        new Thread() {
            @Override
            public void run() {
                synchronized (lock) {
                    System.out.println("I've got lock, but I don't release.");
                    try {
                        Thread.sleep(1000L * 1000);
                    } catch (InterruptedException e) {
                    }
                }
            }
        }.start();

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }

        synchronized (lock) {
            try {
                Thread.sleep(30 * 1000);
            } catch (InterruptedException e) {
            }
        }
    }

    public static void alwaysTimedWaiting() {
        final Object lock = new Object();
        synchronized (lock) {
            try {
                lock.wait(30 * 1000);
            } catch (InterruptedException e) {
            }
        }
    }

    private static void alwaysWaiting() {
        final Object lock = new Object();
        synchronized (lock) {
            try {
                lock.wait();
            } catch (InterruptedException e) {
            }
        }
    }

}
